export const keyPrefix = 'giga-avaliable-';
import { useDirectoryHandle } from '@/entrypoints/hook/useDirectoryHandle';
import { type Dexie as DexieType, type EntityTable } from 'dexie';
import { Dexie } from '@/assets/js/dexie';
import { useRef, useCallback, useEffect } from 'react';

export interface GigaAvaliable {
  id: number;
  skuInfo: string;
  timeStamp: number;
  avaliable: number;
}

export function useAvaliableDB(gigaCatetoryName: string) {
  const dbRef = useRef<(DexieType & { gigaAvaliable: EntityTable<GigaAvaliable, 'id'> }) | null>(
    null,
  );

  const getDB = useCallback(async () => {
    if (dbRef.current) {
      return dbRef.current;
    }
    const isPersisted = await navigator.storage.persisted();
    if (!isPersisted) {
      await navigator.storage.persist();
    }
    // @ts-ignore
    const db = new Dexie(keyPrefix + gigaCatetoryName) as DexieType & {
      gigaAvaliable: EntityTable<GigaAvaliable, 'id'>;
    };
    db.version(1).stores({
      gigaAvaliable: '++id,skuInfo,timeStamp,avaliable',
    });
    dbRef.current = db;
    return db;
  }, [gigaCatetoryName]);

  const addAvaliable = useCallback(
    async (data: Omit<GigaAvaliable, 'id'>) => {
      const db = await getDB();
      const result = await db.gigaAvaliable.add(data);

      // console.log(await db.gigaAvaliable.toArray());
      return result;
    },
    [getDB],
  );

  const deleteAvaliable = useCallback(
    async (id: number) => {
      const db = await getDB();
      const result = await db.gigaAvaliable.delete(id);
      return result;
    },
    [getDB],
  );

  const getAvaliable = useCallback(async () => {
    const db = await getDB();
    const result = await db.gigaAvaliable.toArray();
    // console.log(result);
    return result;
  }, [getDB]);

  // 清除所有数据
  const clearAvaliable = useCallback(async () => {
    const db = await getDB();
    await db.gigaAvaliable.clear();
  }, [getDB]);

  return {
    addAvaliable,
    getAvaliable,
    deleteAvaliable,
    clearAvaliable,
  };
}
